package fr.epsi.spring1.servlets;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;

import fr.epsi.spring1.dao.UserDao;
import fr.epsi.spring1.dao.impl.UserDaoPooledImpl;
import fr.epsi.spring1.domain.User;

/**
 * Servlet implementation class LoginServlet
 */
public class LoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public LoginServlet() {
		super();
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	@Override
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		this.process(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	@Override
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		this.process(request, response);
	}

	public void process(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		Logger.getRootLogger().debug("Login " + request.getParameter("login"));
		String login = request.getParameter("login");
		String password = request.getParameter("password");

		UserDao userDao = new UserDaoPooledImpl();
		User user = userDao.getUser(login);
		if (null != user) {
			if (user.getPassword().equals(password)) {
				Logger.getRootLogger().info("Login " + login + " is autorized");

				response.sendRedirect("accueil.jsp");
				HttpSession session = request.getSession(true);
				session.setAttribute("login", user.getLogin());
				session.setAttribute("admin", user.getIsAdministrator());
			}
		} else {
			Logger.getRootLogger().info("Login " + login + " is rejected");
			response.sendRedirect("login.jsp");
		}
	}
}
